#!/usr/bin/env bash

#===--- swift-stdlib-tool - stand-in for the real swift-stdlib-tool --------===#
#
## This source file is part of the Swift.org open source project
##
## Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
## Licensed under Apache License v2.0 with Runtime Library Exception
##
## See http://swift.org/LICENSE.txt for license information
## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
#===------------------------------------------------------------------------===#

# swift-stdlib-tool substitute for toolchains.
#
# This stand-in for swift-stdlib-tool runs the real swift-stdlib-tool 
# from the XcodeDefault toolchain in $DEVELOPER_DIR.

self_path=$0

tool="$DEVELOPER_DIR/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-stdlib-tool"
if [[ ! -fx "$tool" ]]; then
    echo "$self_path: error: couldn't find swift-stdlib-tool at $tool"
    exit 1
fi

# swift-stdlib-tool sometimes looks for stdlib files relative to itself.
# Perform that lookup here and pass the results to the real swift-stdlib-tool.

argv=("$@")

# Look for an existing --source-libraries argument.
# Look for a --platform argument.
have_source_libraries=NO
platform=""
set -- "$@"
while [[ $# > 0 ]]; do
    case "$1" in
        --source-libraries)
            shift
            if [[ $# > 0 ]]; then
                have_source_libraries=YES
            fi
            ;;
        --platform)
            shift
            if [[ $# > 0 ]]; then
                platform="$1"
            fi
            ;;
    esac
    shift
done


if [[ "$have_source_libraries" = YES ]]; then
    # --source-libraries was already passed. Nothing to do.
    true
elif [[ "$platform" = "" ]]; then
    # platform is unset. Can't continue.
    echo "$self_path: error: neither --platform nor --source-libraries is set."
    exit 1
else
    # Construct a new --source-libraries argument.
    bindir=`dirname "$self_path"`
    usrdir=`dirname "$bindir"`
    source_libraries="$usrdir/lib/swift/$platform"
    if [[ ! -dx "$source_libraries" ]]; then
        echo "$self_path: error: platform path inaccessible: $source_libraries"
        exit 1
    fi
    argv+=("--source-libraries")
    argv+=("$source_libraries")
fi

# Log and run the tool with the new arguments.
echo "$tool" "${argv[@]}"
exec "$tool" "${argv[@]}"
